package com.qfedu.aunt.commons.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.qfedu.aunt.commons.exception.BusinessException;
import com.qfedu.aunt.commons.mapper.RolePermMapper;
import com.qfedu.aunt.commons.pojo.Role;
import com.qfedu.aunt.commons.mapper.RoleMapper;
import com.qfedu.aunt.commons.pojo.RolePerm;
import com.qfedu.aunt.commons.result.ResponseCode;
import com.qfedu.aunt.commons.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.aunt.commons.utils.StringUtil;
import com.qfedu.aunt.commons.vo.RoleAddVo;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaobobo
 * @since 2022-10-31
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermMapper rolePermMapper;

    /**
     * 查询所有的角色
     * @return
     */
    @Override
    public List<Role> findAllRole() {
        List<Role> roles = roleMapper.selectList(null);
        return roles;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addRole(RoleAddVo roleAddVo) throws InvocationTargetException, IllegalAccessException {
        if(null==roleAddVo ||
                StringUtils.isEmpty(roleAddVo.getRoleName())||
                StringUtils.isEmpty(roleAddVo.getRoleDes())||
                 null==roleAddVo.getMenuIds() ||
                 roleAddVo.getMenuIds().size()==0){
            throw new BusinessException(ResponseCode.PARAMETER_ERROR.getCode(),
                    ResponseCode.PARAMETER_ERROR.getMessage());
        }
        //然后程序执行到这里 说明参数没有问题
        //将VO对象转换成PO对象
        Role role = new Role();
        BeanUtils.copyProperties(role,roleAddVo);
        //将role添加到 数据库中去
        roleMapper.insert(role);
        //接下来获取角色id
        String roleId = role.getRoleId();
        //接下来向角色菜单的中间表添加数据
        roleAddVo.getMenuIds().stream().forEach(menuId->{
            //然后组合我们的数据
            RolePerm rolePerm = new RolePerm();
            rolePerm.setRoleId(roleId);
            rolePerm.setPermId(menuId);
            //接下来添加到数据库
            rolePermMapper.insert(rolePerm);
        });
    }
}
